import React, {
  forwardRef,
  memo,
  ReactNode,
  useEffect,
  useImperativeHandle,
  useState
} from 'react'
import {
  Button,
  Dropdown,
  MenuProps,
  Pagination,
  Space,
  Typography
} from 'antd'
import { DownOutlined } from '@ant-design/icons'
import { myShallowEqual, useMyDispatch, useMySelector } from '@/store'
import { fetchPageListAction } from '@/store/module/main/page-common'
import BaseTable from '@/base-ui/base-table'
import { ActionDesc } from '@/global/constant'
import { IContentConfig } from '@/components/page-content/type'
import { HeaderWrapper } from '@/components/page-content/style'
import WithButtonPermission from '@/components/with-button-permission'

interface IProps {
  children?: (
    text: string | number,
    record: any,
    customkey: string
  ) => ReactNode
  headerRightArea?: ReactNode
  config: IContentConfig
  actionClick?: (key: any, record?: any) => void
}

export interface IPageContentRef {
  getPageData: (formData: any) => void
}

const PageContent = (props: IProps, ref: any) => {
  const {
    pageKey,
    isShowAddBtn,
    isShowBatchBtn,
    isShowPagination = true,
    batchActions = []
  } = props.config
  // **************** 数据区 ***************
  const dispatch = useMyDispatch()
  const { tableData, pagination } = useMySelector(
    (state) => ({
      pagination: state.pageCommon.pagination,
      tableData: state.pageCommon.pageList
    }),
    myShallowEqual
  )
  // 使用 useState 定义 formRecord 状态
  const [formRecord, setFormRecord] = useState<any>({})

  useImperativeHandle(ref, () => ({
    getPageData(formData: any) {
      fetchPageData(true, formData)
    }
  }))

  // *************** useEffect *******************
  // 首次加载就获取一次数据 -
  // 配置改变重新获取数据
  useEffect(() => {
    fetchPageData(true)
  }, [props.config])

  // ****************  回调 **************
  // 分页器回调
  function onChange(current: number, size: number) {
    const params = { ...formRecord, current, size }
    const config = {
      pageKey,
      params
    }
    dispatch(fetchPageListAction(config))
  }

  // 请求页面数据
  function fetchPageData(isReSetCurrent: boolean, formData?: any) {
    // 如果是点击按钮查询数据的话，会传来一个新的表单参数，保存下来给分页切换用
    if (formData) {
      setFormRecord(formData)
    }
    // 整理参数
    // console.log('当前的表单参数', formData)
    const { current, size } = pagination
    const params = {
      ...formData,
      current: isReSetCurrent ? 1 : current,
      size
    }
    const config = {
      pageKey,
      params
    }
    dispatch(fetchPageListAction(config))
  }

  // 点击批量操作的情况
  const handleMenuClick: MenuProps['onClick'] = (e) => {
    let key
    switch (e.key) {
      case ActionDesc.BatchDelete:
        key = ActionDesc.BatchDelete
        break
      case ActionDesc.UserBatchBanned:
        key = ActionDesc.UserBatchBanned
        break
      case ActionDesc.UserBatchUniteDisable:
        key = ActionDesc.UserBatchUniteDisable
        break
    }
    props.actionClick?.(key)
  }

  return (
    <>
      <HeaderWrapper>
        <div className="left">
          {isShowAddBtn && (
            <Button
              className="addBtn"
              size="small"
              type="primary"
              onClick={() => props.actionClick?.(ActionDesc.Add)}
            >
              新增
            </Button>
          )}
          {isShowBatchBtn && batchActions.length && (
            <Dropdown
              arrow
              menu={{
                items: batchActions,
                onClick: handleMenuClick
              }}
            >
              <Typography.Link>
                <Space>
                  批量操作
                  <DownOutlined />
                </Space>
              </Typography.Link>
            </Dropdown>
          )}
        </div>
        <div className="right">{props.headerRightArea}</div>
      </HeaderWrapper>
      <BaseTable
        tableData={tableData}
        config={props.config}
        actionClick={props.actionClick}
      >
        {props.children}
      </BaseTable>
      {isShowPagination && (
        <div style={{ textAlign: 'center', marginTop: '15px' }}>
          <Pagination
            current={pagination.current}
            pageSize={pagination.size}
            total={pagination.total}
            showSizeChanger
            showQuickJumper
            onChange={onChange}
            showTotal={(total) => `总${total}条`}
          />
        </div>
      )}
    </>
  )
}

export default memo(WithButtonPermission(forwardRef(PageContent)))
